package jsp.classes;

import java.util.LinkedList;
import jpa.entities.Item;
import jpa.entities.Project;

/**
 * @author Remco Haszing
 */
public class Cache {

    // properties
    private LinkedList<Project> projects = new LinkedList<Project>();
    private LinkedList<Item> items = new LinkedList<Item>();

    // constructor
    /**
     * Creates a cache for finding projects or items that have been used
     * regularly much quicker.
     */
    public Cache() {
    }

    // methods
    /**
     * Cache an object so it can be found much quicker. This method adds a
     * project or item to a linked list, so it can be found in this instance
     * quickly for future use.
     *
     * @param o The object to cache. It should be either a project or an item.
     */
    public void cache(Object o) {
        if (o.getClass() == Project.class) {
            this.projects.add(0, (Project) o);
        } else if (o.getClass() == Item.class) {
            this.items.add(0, (Item) o);
        }
    }

    /**
     * Returns a project with the requested id number. This method returns a
     * project with the requested id number, if it has been cached before.
     *
     * @param id The id number of the project to find.
     * @return The project with the matching id number.
     */
    public Project getProjectById(long id) {
        for (Project p : this.projects) {
            if (p.getId() == id) {
                return p;
            }
        }
        return null;
    }

    /**
     * Returns an item with the requested id number. This method returns an item
     * with the requested id number, if it has been cached before.
     *
     * @param id The id number of the item to find.
     * @return The item with the matching id number.
     */
    public Item getItemById(long id) {
        for (Item i : this.items) {
            if (i.getId() == id) {
                return i;
            }
        }
        return null;
    }
}
